package cn.com.io.day20151211;

import java.io.*;

/**
 * Created by Administrator on 2015/12/11.
 */
public class InsertContent {
    public static void main(String[] args) throws IOException {
         insert(System.getProperty("user.dir")+"\\src\\cn\\com\\io\\day20151211\\InsertContent.java" , 45 , "插入的内容\r\n");
    }

    public static void insert(String fileName , long pos , String insertContent) throws IOException {
        RandomAccessFile raf = null;
        try {
            File temp = File.createTempFile("tmp",null);//创建一个临时文件来保存插入点后的数据
            FileOutputStream tmpOut = null;
            FileInputStream tmpIn = null;
            temp.deleteOnExit();

            raf = new RandomAccessFile(fileName,"rw");
            tmpOut = new FileOutputStream(temp);
            tmpIn = new FileInputStream(temp);
            raf.seek(pos);
            /*将插入点后的内容读入临时文件中保存*/
            byte [] buf = new byte[64];
            int hasRead = 0;//用于保存实际读取的字节数
            while((hasRead = raf.read(buf)) > 0){
                tmpOut.write(buf, 0 , hasRead);//将读取的数据写入临时文件
            }
            /*插入内容*/
            raf.seek(pos);//把文件记录指针重新定位到pos位置
            raf.write(insertContent.getBytes());//追加需要插入的内容
            while((hasRead = tmpIn.read(buf)) > 0){
                //追加临时文件中的内容
                raf.write(buf , 0 ,hasRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (raf != null ){
                raf.close();
            }
        }
    }
}
